<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             class="full-form"
             label-width="100px"
             status-icon>

      <el-form-item label="手机号：" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号"/>
      </el-form-item>
<!--      <el-form-item label="账号：">-->
<!--        <el-input v-model="formData.account" placeholder="请输入账号"/>-->
<!--      </el-form-item>-->
      <el-form-item :rules="isCreate<=0 ? [{required: true, message: '密码不能为空', trigger: 'change'}] : []" label="密码：" prop="password">
        <el-input v-model="formData.password" placeholder="请输入密码"/>
      </el-form-item>

      <el-form-item label="昵称：" prop="name">
        <el-input v-model="formData.name" placeholder="请输入昵称"/>
      </el-form-item>



<!--      <el-form-item label="邮箱：" prop="email">-->
<!--        <el-input v-model="formData.email" placeholder="请输入邮箱"/>-->
<!--      </el-form-item>-->

      <el-form-item label="头像：">
        <UploadImage v-model="formData.head" :disabled="readonly" :show-delete="true"/>
      </el-form-item>

<!--      <el-form-item label="状态：" prop="enabled">-->
<!--        <el-radio-group v-model="formData.enabled" size="small">-->
<!--          <el-radio :value="true" border>启用</el-radio>-->
<!--          <el-radio :value="false" border>禁用</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->

      <el-form-item label="角色权限：">
<!--        <el-checkbox-group v-model="formData.rid">-->
<!--          <el-checkbox v-for="item in roleList" :key="item.id" :value="item.id">-->
<!--            {{ item.name }}-->
<!--          </el-checkbox>-->
<!--        </el-checkbox-group>-->
                <el-radio-group v-model="formData.rid" size="small">
                  <el-radio v-for="(item,index) in roleList" :key="index" :value="item.id" border>{{item.name}}</el-radio>
                </el-radio-group>
      </el-form-item>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['sys:user:create', 'sys:user:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import {
  SysRoleData,
  sysUserAdd,
  sysUserUpdate,
  sysUserInfo,
  sysUserSaveOrUpdate, sysRoleList
} from '@/api/api-sys.ts';
import { UploadImage } from '@/components/upload';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';

defineOptions({name: 'SysUserForm'})

const formRef = ref<FormInstance>();
const formLoading = ref(false);// 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 默认表单数据
let defaultForm = {
  id: 0,
  account: '',
  password: '',
  name: '',
  phone: '',
  head: '',
  rid:''
};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  account: [{required: true, message: '账号不能为空', trigger: 'change'}],
  name: [{required: true, message: '昵称不能为空', trigger: 'change'}],
  phone: [{required: true, message: '手机号不能为空', trigger: 'change'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value || roleLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = ref();

// 角色列表
const roleList = ref<SysRoleData[]>([]);
const roleLoading = ref(false)
const initRoleData = async () => {
  roleLoading.value = true
  try {
    const {body} = await sysRoleList({
      page: 1,
      size: 200,
      action:'list',
    });
    roleList.value = body.list
  } finally {
    roleLoading.value = false
  }
};

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '系统账号';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();

  // 加载权限菜单
  await initRoleData();
  isCreate.value=id
  // 加载数据
  if (id) {
    formLoading.value = true
    try {
      // 加载用户数据
      const {body} = await sysUserInfo({id:id,action:'info'})
      formData.value = body;
      formData.value.password = ''
    } finally {
      formLoading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // 提交数据
    if(isCreate.value<=0){
      sysUserAdd(formData.value, {action:'add'}).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 发送操作成功的事件
        emit('refresh')
        // 隐藏窗口
        dialogVisible.value = false
      }).finally(() => loading.close())
    }else{
      delete formData.value.password
      sysUserUpdate(formData.value, {action:'update'}).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 发送操作成功的事件
        emit('refresh')
        // 隐藏窗口
        dialogVisible.value = false
      }).finally(() => loading.close())
    }

  });
};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-checkbox-group .el-checkbox {
    float: left;
    width: 150px;
    padding-right: 10px;
    margin: 0;
  }
}
</style>
